<?php
/**
 * 文章
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/6
 * Time: 22:34
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use app\common\model\Attachment as AttachmentModel;
use app\common\model\BoolStatus;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleDetail as ArticleDetailModel;
use app\admin\validate\Article as ArticleValidate;
use app\common\model\Category as CategoryModel;
use base\BaiduPush;
use think\Cache;
use think\Config;
use think\Db;
use think\exception\ErrorException;
use app\common\model\Position as PositionModel;
use app\common\model\PositionContent as PositionContentModel;

class Article extends AdminBase
{
    /**
     * 文章列表
     * @return mixed
     */
    public function index()
    {
        $articleModel = new ArticleModel();
        $list         = $articleModel->paginate($this->pageSize);

        // 获取分页显示
        $page = $list->render();
        // 模板变量赋值
        $this->assign('list', $list);
        $this->assign('page', $page);

        $status = BoolStatus::getLables();
        $this->assign('status', $status);

        $position = PositionModel::all();
        $this->assign('position', $position);

        return $this->fetch('article/index');
    }

    /**
     * 设置文章信息
     * @return mixed
     */
    public function set()
    {
        $id           = $this->request->param('id', 0, 'int');
        $articleModel = new ArticleModel();
        if ($this->request->isPost()) {
            $subject      = $this->request->param('subject');
            $cid          = $this->request->param('cid');
            $status       = $this->request->param('status', BoolStatus::OPEN, 'int');
            $dis_order    = $this->request->param('dis_order', 99, 'int');
            $content      = $this->request->param('content');
            $seo_title    = $this->request->param('seo_title');
            $seo_keywords = $this->request->param('seo_keywords');
            $seo_desc     = $this->request->param('seo_desc');
            $aids         = $this->request->param('aids');
            //验证数据
            $validate = new ArticleValidate();
            if (!$validate->check(['subject' => $subject, 'status' => $status, 'cid' => $cid, 'dis_order' => $dis_order])) {
                $this->error($validate->getError());
            }
            Db::startTrans();
            try {
                $currentTime = time();
                if (!$id) {
                    //新增
                    $count = $articleModel->where('subject', '=', $subject)->count();
                    if ($count) {
                        $this->error('该文章标题已存在，请输入其他的文章标题~~');
                    }
                    $articleModel->created_time = $currentTime;
                    $articleModel->viewed       = 0;
                } else {
                    //编辑
                    $count = $articleModel->where('subject', '=', $subject)->whereNotIn('id', $id)->count();
                    if ($count) {
                        $this->error('该文章标题已存在，请输入其他的文章标题~~');
                    }
                    $articleModel = $articleModel->find($id);
                }
                $articleModel->cid          = $cid;
                $articleModel->dis_order    = $dis_order;
                $articleModel->uid          = $this->currentUser->id;
                $articleModel->updated_time = $currentTime;
                $articleModel->subject      = $subject;
                $articleModel->status       = $status;
                $result                     = $articleModel->save();
                if (!$result) {
                    $this->error('操作失败~~');
                }

                $articleDetail = new ArticleDetailModel();
                if (!$id) {
                    //新增
                    $articleDetail->id = $articleModel->id;
                } else {
                    //编辑
                    $articleDetail = $articleDetail->find($id);
                }
                $articleDetail->content      = $content;
                $articleDetail->seo_title    = $seo_title;
                $articleDetail->seo_keywords = $seo_keywords;
                $articleDetail->seo_desc     = $seo_desc;
                $articleDetail->updated_time = $currentTime;
                $result                      = $articleDetail->save();
                if (!$result) {
                    $this->error('操作失败~~~');
                }

                if ($aids) {
                    $aidArr = explode(',', $aids);
                    foreach ($aidArr as $aid) {
                        AttachmentModel::update(['tid' => $articleModel->id, 'type' => AttachmentModel::ARTICLE], ['aid' => $aid]);
                    }
                }

                Db::commit();

            } catch (ErrorException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('操作成功~~', url('admin/article/index'));

        }
        $article = $articleDetail = null;
        if ($id) {
            $article       = $articleModel->find($id);
            $articleDetail = ArticleDetailModel::find($id);
        }
        $this->assign('article', $article);
        $this->assign('articleDetail', $articleDetail);

        //分类
        $cids = CategoryModel::where('status', '=', BoolStatus::OPEN)->column('id, name, pid');
        $this->assign('cids', generateTree($cids));

        //开关
        $status = BoolStatus::getLables();
        $this->assign('status', $status);

        //附件
        $attach = AttachmentModel::where('tid', '=', $id)->where('type', '=', AttachmentModel::ARTICLE)->find();
        $this->assign('attach', $attach);
        return $this->fetch('article/set');
    }

    /**
     * 推送
     */
    public function push()
    {
        $ids        = $this->request->param('ids');
        $positionId = $this->request->param('positionId');
        if (!$ids) {
            $this->error('请选择要设置推送的文章');
        }
        if (!$positionId) {
            $this->error('请选择推荐位');
        }
        $idArr = explode(',', $ids);

        Db::startTrans();

        try {

            $articleModel = new ArticleModel();
            $list         = $articleModel->whereIn('id', $idArr)->select();

            foreach ($list as $item) {
                $data  = [
                    'position_id'  => $positionId,
                    'title'        => $item['subject'],
                    'thumb'        => '',
                    'news_id'      => $item['id'],
                    'status'       => BoolStatus::OPEN,
                    'url'          => url('@index/item/index', 'id=' . $item['id']),
                    'created_time' => date('Y-m-d H:i:s', time()),
                    'updated_time' => date('Y-m-d H:i:s', time()),
                ];
                $model = new PositionContentModel();
                $model->save($data);
            }

            Db::commit();
        } catch (ErrorException $e) {
            Db::rollback();
        }

        $this->success('操作成功~~');
    }

    public function baiduPush()
    {
        $ids = $this->request->param('ids');
        if (!$ids) {
            $this->error('请选择要设置推送的文章');
        }
        $idArr        = explode(',', $ids);
        $articleModel = new ArticleModel();
        $idArr        = $articleModel->whereIn('id', $idArr)->column('id');

        $config = Config::get('baiduPush');
        $site   = $config['site'];
        $token  = $config['token'];

        $viewSuffix = Config::get('template.view_suffix');

        foreach ($idArr as $id) {
            $urlArr[] = url('@index/item/index', 'id=' . $id, $viewSuffix, $site);
        }
        $result = BaiduPush::init($site, $token)->push($urlArr);
        $result = json_decode($result, true);
        if (isset($result['success'])) {
            $this->success("本次成功推送{$result['success']}条,当天剩余的可推送{$result['remain']}条url地址");
        } else {
            $this->error("推送失败 {$result['error']}:{$result['message']}");
        }
    }
}